<template>
  <div>
    <FormPanel ref="form" :list="formList" formType="add" :isSubmitBtn="false" labelWidth="120" columnsRef="zjpjkcemitStock" @formChange="changeHandle" />
    <div
      :style="{
        position: 'absolute',
        left: 0,
        bottom: 0,
        right: 0,
        zIndex: 9,
        borderTop: '1px solid #e9e9e9',
        padding: '10px 20px',
        background: '#fff',
        textAlign: 'right'
      }"
    >
      <!-- <p class="test">说明:成本价不含税</p> -->
      <el-button @click="closeDrawer(1)">取 消</el-button>
      <el-button type="primary" @click="closeDrawer(2)">保 存</el-button>
    </div>
    <!-- 库位 -->
    <BaseDialog :visible.sync="positionSelectVisible" title="库位选择" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <position :params="positionParams" @close="positionSelectVisible = false" @onConfirm="handlePositionSelectConfirm" />
    </BaseDialog>
  </div>
</template>
<script>
import {
  edit,
  getDealertCode,
  getfindStorageCode,
  getquerypartGroupCodes,
  getpartInfos,
  getStockQuantity,
  getPosition,
  save,
  getStockOutInQuantity
} from '@/api/part/inventoryManager/inventoryManager/index';
import { dictionary } from '@/utils/dictMixin';
import { addPartInfo, ModifyPartInfo, queryUnitCode } from '@/api/part/partInfo';
import { getBrandList } from '@/api/common/cars/masterDataCars';
import pinyin, { STYLE_FIRST_LETTER } from '@/components/Pinyin/index';
import { findAllRepair } from '@/api/repair/basicParameters';
import { isAuthorized } from '@/utils/index';
import position from '@/pages/part/common/position';
import { getPinpSelect } from '@/api/repair/repairReception/customer/brand.js';
export default {
  components: {
    position
  },
  mixins: [dictionary],
  props: ['getdata'],
  data() {
    // this.basetable = null;
    return {
      formList: this.createFrom(),
      partInfoList: [],
      commitData: {},
      tableList: [],
      params: Object.assign({}, { xhrAbort: false }, { partNo: this.getdata.partNo, storageCode: this.getdata.storageCode }),
      positionSelectVisible: false, // 是否显示库位选择弹窗
      positionParams: {}
    };
  },
  computed: {},
  watch: {},
  created() {
    this.getDictlist();
    this.initData();
  },
  mounted() {
    // this.basetable = this.$refs.basetable.$refs.pageTable;
  },
  methods: {
    // 选择库位(弹窗)
    handlePositionSelectConfirm(val) {
      this.formList.find(item => item.fieldName == 'storagePositionCode').initialValue = val[0].storagePositionCode;
      this.positionSelectVisible = false;
    },
    // 点击库位搜索
    handleSearchPosition() {
      let storageCode = this.formList.find(item => item.fieldName == 'storageCode').initialValue;
      if (!storageCode) {
        return this.$notify.warning({ title: '提示信息', message: '请选择仓库' });
      }
      this.positionParams.storageCode = storageCode;
      // this.positionParams.partNo = this.formList.find(item => item.fieldName == 'partNo').initialValue;
      this.positionSelectVisible = true;
    },

    async queryEmptyLocation(val) {
      let res = await getPosition({ storageCode: val });
      if (res.resultCode === 200) {
        this.formList.find(item => item.fieldName === 'storagePositionCode').itemList = res.data.map(x => ({ text: x.storagePositionCode, value: x.storagePositionCode }));
      }
    },
    initData() {
      for (let i in this.getdata) {
        for (let j = 0; j < this.formList.length; j++) {
          if (this.formList[j].fieldName == i) {
            this.formList[j].initialValue = this.getdata[i];
          }
          if (this.formList[j].fieldName == 'minPackage') {
            this.formList[j].initialValue = this.getdata['packageLiaght'];
          }
          if (this.formList[j].fieldName == 'partStatus') {
            this.formList[j].initialValue = '' + this.getdata['partStatus'];
          }
        }
      }
      this.queryEmptyLocation(this.getdata.storageCode);
    },

    createFrom() {
      return [
        // {
        //   type: 'SELECT',
        //   label: '品牌',
        //   fieldName: 'brand',
        //   placeholder: '请选择...',
        //   initialValue: '',
        //   disabled: true,
        //   itemList: [
        //     { text: 'BEIJING', value: 'beqi' },
        //     { text: 'ARCFOX', value: 'arc' }
        //   ]
        // },
        {
          type: 'INPUT',
          label: '配件代码',
          fieldName: 'partNo',
          initialValue: '',
          disabled: true,
          disabled: true
        },
        {
          type: 'INPUT',
          label: '配件名称',
          fieldName: 'partName',
          disabled: true,
          initialValue: '',
          rules: [{ required: true, message: '请输入配件名称', trigger: 'blur' }],
          onInput: e => {
            this.formList.find(item => item.fieldName == 'spellCode').initialValue = pinyin(e, { style: STYLE_FIRST_LETTER })
              .flat()
              .join('');
          },
          change: props => {
            this.changePartName(props);
          }
        },
        {
          type: 'SELECT',
          label: '数据来源',
          fieldName: 'downTag',
          disabled: true,
          itemList: [
            { text: '厂端下发', value: 10041001 },
            { text: '店端自建', value: 10041002 }
          ]
        },
        {
          type: 'SELECT',
          label: '仓库',
          fieldName: 'storageCode',
          placeholder: '请选择',
          disabled: true,
          itemList: [],
          rules: [{ required: true, message: '请输入仓库', trigger: 'blur' }],
          change: this.queryEmptyLocation
        },
        {
          type: 'INPUT',
          label: '库位代码',
          fieldName: 'storagePositionCode',
          initialValue: '',
          rules: [{ required: true, message: '请输入库位', trigger: 'blur' }],
          // itemList: [],
          unitRender: () => {
            return <el-button slot="append" icon="el-icon-search" onClick={this.handleSearchPosition}></el-button>;
          }
          // disabled: true
        },
        {
          type: 'INPUT_NUMBER',
          precision: 2,
          label: '成本单价',
          fieldName: 'costPrice',
          initialValue: '',
          disabled: true
        },
        {
          type: 'SELECT',
          label: '状态',
          fieldName: 'partStatus',
          placeholder: '请选择',
          disabled: false,
          itemList: [
            { text: '停用', value: '10041001' },
            { text: '启用', value: '10041002' }
          ],
          change: this.queryEmptyLocation
        },
        // {
        //   type: 'INPUT',
        //   label: '加价率',
        //   fieldName: 'ADD_RATE',
        //   initialValue: '',
        // },

        {
          type: 'INPUT_NUMBER',
          precision: 2,
          label: '库存数量',
          fieldName: 'stockQuantity',
          initialValue: '',
          disabled: true
        },
        {
          type: 'INPUT_NUMBER',
          precision: 2,
          label: '可用库存',
          fieldName: 'usableQuantity',
          initialValue: '',
          disabled: true
        },
        {
          type: 'INPUT_NUMBER',
          precision: 2,
          label: '锁定量',
          fieldName: 'lockedQuantity',
          initialValue: '',
          disabled: true
        },
        // {
        //   type: 'INPUT_NUMBER',
        //   label: '建议销售价',
        //   fieldName: 'notTaxInstructPrice',
        //   initialValue: '',
        //   disabled: true
        // },
        {
          type: 'INPUT_NUMBER',
          precision: 2,
          label: '最大库存',
          fieldName: 'maxStock',
          initialValue: ''
        },
        {
          type: 'INPUT_NUMBER',
          precision: 2,
          label: '最小库存',
          fieldName: 'minStock',
          initialValue: ''
        },
        {
          type: 'INPUT_NUMBER',
          precision: 2,
          label: '安全库存',
          fieldName: 'safeStock',
          initialValue: ''
        },
        {
          type: 'INPUT',
          label: '呆滞天数',
          fieldName: 'sluggishDays',
          disabled: true,
          initialValue: ''
        }

        // {
        //   type: 'INPUT_NUMBER',
        //   precision: 2,
        //   label: '终端建议零售价格',
        //   fieldName: 'insurancePrice',
        //   initialValue: ''
        // },
        // {
        //   type: 'INPUT',
        //   label: '替代配件',
        //   fieldName: 'optionNo',
        //   initialValue: '',
        //   disabled: true
        // },
      ];
    },
    createTable() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          sorter: true,
          render: props => {
            return <span>{props.row.$index + 1}</span>;
          }
        },
        {
          title: '年度',
          dataIndex: 'YEAR',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '月度',
          dataIndex: 'month',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '出库数量',
          dataIndex: 'outQuantity',
          sorter: true,
          filter: true,
          precision: 2,
          filterType: 'number'
        },
        {
          title: '入库数量',
          dataIndex: 'inQuantity',
          sorter: true,
          filter: true,
          precision: 2,
          filterType: 'number'
        }
      ];
    },
    tablechangeFun() {},
    changeHandle(val) {
      console.log(val);
      this.commitData = val;
    },
    async closeDrawer(type) {
      if (type == 1) {
        this.$emit('close', false);
      } else {
        this.commitData = this.$refs.form.SUBMIT_FORM();
        console.log(this.commitData.stockQuantity, '配件库存数量');
        // 配件库存数量是零 库位才可以不选择
        if (this.commitData.storagePositionCode == '') {
          if (this.commitData.stockQuantity != 0) {
            this.$notify.warning({ title: '提示信息', message: '配件库存数量是0，才能清空库位' });
            return;
          }
        }

        this.commitData['flg'] = 'U';

        let obj = { dmstable: [this.commitData], dmsTable: [this.commitData] };
        // obj = JSON.parse(JSON.stringify(obj));
        let res = await save(obj);
        if (res.resultCode == '200') {
          this.$notify.success({ title: '提示信息', message: '保存成功' });
          this.$emit('addChange');
        }
      }
    },
    // 查询品牌
    async getBrand() {
      // const res = await getBrandList();
      const res = await getPinpSelect();
      this.formList.find(item => item.fieldName == 'brand').itemList = res.data.map(x => ({ text: x.brandName, value: x.brandCode + '' }));
    },
    // 获取数据字典
    async getDictlist() {
      let res = (await getfindStorageCode(this.fetchParams)).data.map(x => ({ text: x.STORAGE_NAME, value: x.STORAGE_CODE }));
      this.formList.find(item => item.fieldName === 'storageCode').itemList = res;
      // this.getBrand();
      // this.formList[0].itemList = res;
      // console.log(res, 'res');
      let res2 = await getpartInfos(this.fetchParams);
      this.partInfoList = res2;
      let res1 = (await getquerypartGroupCodes(this.fetchParams)).data.map(x => ({ text: x.PART_MODEL_GROUP_NAME, value: x.PART_MODEL_GROUP_CODE }));
      let storageCode = this.formList.find(item => item.fieldName === 'storageCode').initialValue;
      let partNo = this.formList.find(item => item.fieldName === 'partNo').initialValue;
      const res4 = await queryUnitCode();
      // this.formList.find(item => item.fieldName == 'unitCode').itemList = res4.data.map(x => ({ text: x.UNIT_NAME, value: x.UNIT_CODE }));
      let res5 = await findAllRepair();
      // this.formList.find(item => item.fieldName == 'taxRate').initialValue = res5.data['1003'];
      // this.basetable.EXECUTE_INSERT(res3.data);
    },
    changePartName(val) {
      console.log(val, this.partInfoList, 'this.partInfoList');
      let is = false;
      for (let i = 0; i < this.partInfoList.length; i++) {
        if (this.partInfoList[i].value == val) {
          is = true;
        }
      }
      if (is) {
        this.$confirm('配件代码重复是否确定？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {})
          .catch(() => {
            this.formList[8].initialValue = '';
          });
      }
    }
  }
};
</script>
<style lang="less" scoped>
.test {
  text-align: left;
  color: red;
  display: block;
  float: left;
}
</style>
